<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use app\wh\model\Color as ColorModel;
use app\wh\model\Stock as StockModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\Supplier as SupplierModel;
use think\Db;

/**
 * 物料模型
 */
class Material extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'wh_material';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //采购状态
    public static $status = [
        -1 =>     '审核未通过',
        0 =>      '待审核',
        1 =>      '未入库',
        2 =>      '仓库收货',
        3 =>      '已入库',
    ];
    //采购状态
    public static $status_bar = [
        0 =>      '发起采购',
        1 =>      '审核通过',
        2 =>      '仓库收货',
        3 =>      '已入库',
    ];
    //采购需求状态
    public static $urgent_status = [
        0 =>      '一般需求',
        1 =>      '紧急需求',
        2 =>      '加急需求',
    ];
    //采购打印条码状态
    public static $code_print_status = [
        0 =>      '待打印',
        1 =>      '已打印',
    ];
    //油温
    public static $heat = [
        0 =>      '无油温',
        1 =>      '中温',
        2 =>      '高温',
    ];
    //油温编码
    public static $heat_code = [
        0 =>      '',
        1 =>      'Z',
        2 =>      'G',
    ];
    //自定义状态标签
    public static function urgent_status_color($status=0,$label=''){
        switch ($status) {
            case '0': $class = ' bg-white';break;
            case '1': $class = ' bg-info-light';break;
            case '2': $class = ' bg-danger-light';break;
            case '3': $class = ' bg-danger-light';break;
            case '-1': $class = 'primary';break;
            case '-2': $class = 'primary';break;
            default: $class  = 'default';
        }
        $label = '<a class="btn-'.$class.'">'.$label.'</a>';

        return $label;
    }
    //状态进度条
    public static function status_bar_tag($status=0){

        //进度条
        $status_bar = self::$status_bar;
        //审核状态
        if($status < 2)$status_bar[1] = self::$status[$status];

        if($status < 0)$status = 0;

        $key = array_search($status,array_keys($status_bar));
        $bar = ($key/count($status_bar))*100;
        $bar = 100;

        $label = '<div class="layui-progress mar_t_20" lay-showpercent="true"><div class="layui-progress-bar badge-primary" style="width: '.$bar.'%;" lay-percent="'.$bar.'/100"><span class="layui-progress-text badge-primary">'.$bar.'%</span></div></div>';

        return $label;
    }
    //获取库存
    public static function getSumNumber($data = []){

        $input['stock_sn'] = empty($data['stock_sn'])?'':$data['stock_sn'];
        $input['supplier_id'] = empty($data['supplier_id'])?'':$data['supplier_id'];
        $input['type_pid'] = empty($data['type_pid'])?'':$data['type_pid'];
        $input['type_id'] = empty($data['type_id'])?'':$data['type_id'];
        $input['model'] = empty($data['stock_sn'])?'':$data['model'];

        $where = [];
        if(!empty($input)){
            foreach ($input as $k=>$v){
                $where[] = [$k,'=',$v];
            }
        }

        if(!empty($where))$num = Db::name('wh_stock')->where($where)->value('number');
        if(empty($num))$num = '暂无库存';

        return $num;
    }
    // 采购单号
    public static function getMaterialSn(){

        $number = Db::name('wh_material')->order('id desc')->value('id');
        $number = intval($number)+1;

        return "XXCQ".date('Ymd').$number;
    }
    // 采购单表单设计
    public static function getTabFrom($pid = 0,$data = [],$print = 0){

        $from = [];

        switch ($pid) {
            case in_array($pid,ColorModel::$type_pid_arr)://油漆库
                if(empty($data['is_order_color']))$from = self::from1NotOrderColor($pid,$data,$print);
                elseif(empty($data['id']) && empty($data['order_ids']))$from = self::fromSelect($pid);
                else $from = self::from1($pid,$data,$print);
                break;
            case 3://型材
                $from = self::from4($pid,$data,$print);
                break;
            case 4://铝卷
                $from = self::from4($pid,$data,$print);
                break;
            case 5://铝板
                $from = self::from5($pid,$data,$print);
                //$from = self::from4($pid,$data,$print);
                break;
            case 2://化工
            default://其他
                $from = self::from6($pid,$data,$print);
                break;
        }

        return $from;

    }

    //选择工程
    //print 0:编辑模式 1:打印模式 2:导出
    public static function fromSelect($type_pid = '',$isajax = false,$where = []){

        //---------------------------------------------工程表单项 start------------------------------------------
        $feild = 'selectorder';
        $feild2 = 'selectorder2';

        $supplier_list = SupplierModel::getGroup(0,$type_pid,'title_abb');
        $table_search = [[
            "[12:1]
            <div id='form-ajax-search' action='".url('wh/material/selectorder',['stock_type'=>$type_pid])."' data-select='{$feild}' data-select2='{$feild2}' class='flex flex-center flex-center-right form-right' style='float:right'>
            <div class=\"d-input input-group d-input1\" data-width=\"1\"><span class=\"input-group-addon\">档案编码</span>".self::inputToText('o.archives_sn','',0,'','input','form-ajax-search','','',['_o'=>'like'])."</div>
            <div class=\"d-input input-group d-input1\" data-width=\"1\"><span class=\"input-group-addon\">工程名称</span>".self::inputToText('o.engineering','',0,'','input','form-ajax-search','','',['_o'=>'like'])."</div>
            <div class=\"d-input input-group d-input1\" data-width=\"1\"><span class=\"input-group-addon\">供应商</span>".self::inputToText('c.supplier_id','',0,'','select','form-ajax-search',$supplier_list,'',['_o'=>'eq'])."</div>
            <div class=\"d-input input-group d-input1\" data-width=\"1\"><span class=\"input-group-addon\">颜色编号</span>".self::inputToText('c.supplier_color','',0,'','input','form-ajax-search','','',['_o'=>'like'])."</div>
            <div class=\"d-input input-group d-input1\" data-width=\"1\"><span class=\"input-group-addon\">优先级</span>".self::inputToText('o.point','',0,'','select','form-ajax-search',self::$urgent_status,'',['_o'=>'like'])."</div>
            <div class=\"d-input input-group d-input1\" data-width=\"1\"><span class=\"input-group-addon\">交货日期</span>".self::inputToText('o.point_time','',0,'','date','form-ajax-search','','',['_o'=>'like'])."</div>
                    <div class='input-group'><button type='button' class='layui-btn layui-btn-xs' data-form='form-ajax-search' onclick=\"ajax_search(this)\">搜索</button></div>
                    <div class='input-group'><button type='button' class='layui-btn layui-btn-xs layui-btn-reset' data-form='form-ajax-search' onclick=\"ajax_search(this,'reset')\">重置</button></div>
                    <a style='float:right;' class='btn btn-primary notPrint' href='".url('wh/material/add',['stock_type'=>$type_pid,'is_order_color'=>0])."'>发起采购</a>
            </div>",
            ]];
        $table_data = [];

        $map = [];
        if(is_numeric($type_pid))$map[] = ['c.type_pid','=',$type_pid];

        if(empty($where)){
            $map[] = ['c.status','=',1];
            $where = '1=1';
        }
        $list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,mc.nickname,mc.back,mc.sales,sum(c.row_area) as color_row_area,c.archives_number')
            ->leftJoin('wh_order_color c','o.id=c.order_id')
            ->leftJoin('mill_client mc','mc.id=o.client_id')
            ->where($map)
            ->where($where)
            ->group('o.id')
            ->order('o.id desc')
            ->select();

        //二级列表表头
        $head = [
            'color_sn'              =>  ['color_sn', '系统编号'],
            'supplier_id'           =>  ['supplier_id', '供应商',$supplier_list],
            'supplier_color'        =>  ['supplier_color', '颜色编号'],
            'color'                 =>  ['color', '面积表颜色'],
            'type_pid'              =>  ['type_pid', '关联样板'],
            'type_id'               =>  ['type_id', '类别',StockTypeModel::getGroup($type_pid)],
            'color_type_id'         =>  ['color_type_id', '类型',ColorModel::getColorType()],
            'quality'               =>  ['quality', '属性',ColorModel::getQuality()],
            'heat'                  =>  ['heat', '油温',self::$heat],
            'stock_number'          =>  ['stock_number', '库存量(KG)'],
            'row_area'              =>  ['row_area', '待喷涂面积(M²)'],
            'sug_number'            =>  ['sug_number', '建议建议量(KG)'],
            'quality2'              =>  ['quality', '涂层',ColorModel::getQuality()],
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];

        foreach ($list as $v){

            //工程信息
            /*$table_data[] = [
                "[12:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>档案号：{$v['archives_sn']}</span>
                            <span>工程名称：{$v['engineering']}</span>
                            <span>客户名称：{$v['nickname']}</span>
                            <span>内勤：{$v['back']}</span>
                            <span>业务代表：{$v['sales']}</span>
                            <span>总面积：{$v['color_row_area']}</span>
                            <span>总数量：{$v['archives_number']}</span>
                            <span>查看板型</span>

						</div>
					</div>",

            ];*/
            $table_data[] = [
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>档案号：</span>

						</div>
					</div>",
                "[2:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>{$v['archives_sn']}</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>工程名称：</span>

						</div>
					</div>",
                "[2:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>{$v['engineering']}</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>跟单：我</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>业务：{$v['sales']}</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>总面积：{$v['color_row_area']}</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>总数量：{$v['archives_number']}</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>优先级：高</span>

						</div>
					</div>",
                "[2:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
                            <span>交货日期：".date('Y-m-d',$v['create_time'])."</span>

						</div>
					</div>",
                "[1:1]<div class=\"layui-row layui-col-space10 layui-btn-blue new-table-head\" data-order-id='{$v['id']}'>

						<div class=\"layui-col-md12 new-table-head-flex\">
						<span>&nbsp;</span>
                        </div>
					</div>",

            ];

            //定色表头
            $v_head = [];
            foreach ($head as $hk=>$hv){
                $v_head[] = '<div class="new-table-head-2">'.$hv[1].'</div>';
            }
            $table_data[] = $v_head;

            //定色列表
            $color_list = Db::name('wh_order_color')->where(['order_id'=>$v['id'],'type_pid'=>$type_pid,'status'=>1])->select();
            foreach ($color_list as $c){
                //获取库存
                $c['stock_number'] = StockModel::getSumNumber($c);

                //根据定色表头顺序，组装数据
                $v_data = [];
                foreach ($head as $hk=>$hv){
                    //如果表头3为“btn”，则为操作按钮
                    if(!empty($hv[2]) && $hv[2] == 'btn'){
                        $v_data[] = "
                            <a class='btn btn-primary new-table-list-add' onclick='select_order_ids(this)' data-order-id='{$c['order_id']}' data-id='{$c['id']}' data-select='{$feild}' data-select2='{$feild2}'>订购</a>
                            <a class='btn btn-danger new-table-list-del' data-type-pid='{$type_pid}' data-order-id='{$c['order_id']}' data-id='{$c['id']}' data-select='{$feild}' data-select2='{$feild2}' data-href='".url('wh/material/rationSubs')."' onclick='select_order_del(this)'>移除</a>
                        ";
                    }
                    //如果表头3不为空，则为下拉数据
                    elseif(!empty($hv[2]))$v_data[] = isset($hv[2][$c[$hv[0]]])?$hv[2][$c[$hv[0]]]:'';
                    else $v_data[] = isset($c[$hv[0]])?$c[$hv[0]]:'';
                }

                $table_data[] = $v_data;
            }

        }

        $table_head2 = "[12:1]<div class='layui-row layui-col-space10 layui-bg-black new-table-head' data-order-id=''>

						<div class='layui-col-md12 new-table-head-flex'>
                            <span style='margin-left: -15px;'>加入数量<span id='list-sum' class='badge badge-danger list-sum'>0</span></span>
                            <span style='text-align: center;cursor: pointer;' data-type='show' data-select='{$feild}' data-select2='{$feild2}' onclick='select_order2_show(this)'>查看</span>
                            <span style='text-align: right;cursor: pointer;' data-select='{$feild}' data-select2='{$feild2}'  onclick='select_get(this)'>生成采购单：".self::getMaterialSn()."</span>

						</div>
					</div>";
        //设置表单项
        $from[] = ['complexTable:12', 'selectorder_search', '', $table_search,''];
        $from[] = ['complexTable:12', $feild, '', $table_data, ''];
        $from[] = ['complexTable:12', 'selectorder_search2', '', [[$table_head2]], []];
        $from[] = ['complexTable:12', $feild2, '', [], []];
        //---------------------------------------------工程表单项 end--------------------------------------------

        //CSS
        $css = "<style>
                #table-selectorder_search > tbody > tr > td{border: hidden;}
                #table-selectorder > tbody > tr > td:has(.new-table-head){padding: unset;border-bottom: hidden;border-left: hidden;border-right: hidden;}
                #table-selectorder > tbody > tr > td:has(.new-table-head-2){background-color: #F2F2F2;font-weight: bold;}
                #table-selectorder > tbody > tr > td{text-align: center;}
                
                #table-selectorder_search2{padding: unset;border: hidden;}
                #table-selectorder_search2 > tbody > tr > td{padding: 0 5px 0 0;border: hidden;}
                #form_group_selectorder_search2 {margin-top: -24px;}
                
                #table-selectorder2 > tbody > tr > td:has(.new-table-head){padding: unset;border: hidden;}
                #form_group_selectorder2 {display: none;background-color:#fff;height:300px;margin-top:-255px;overflow-x:scroll}
            </style>";
        //JS
        $js = '<script src="'.config('template.tpl_replace_string')['__STATIC__'].'/home/js/fly.js?v='.date('Ymd').'"></script>';
        $js .= '<script type="text/javascript">
                //根据页面高度设置滚动条
                var height = $(window).height();
                var _top = $("#form_group_selectorder").offset().top;
                var bottom = 60;
                $("#form_group_selectorder").css("height",(height-_top-bottom)+"px");
                $("#form_group_selectorder").css("overflow-x","scroll");
                $(".hidden-border-left-right").parent("td").css("border-left","hidden");
                $(".hidden-border-left-right").parent("td").css("border-right","hidden");
                
                //搜索
                function ajax_search(obj,type = "") {
                    var form = $(obj).parents("#"+$(obj).data("form"));
                    //var form = $(obj).parents("form");
                    var href = form.attr("action");//ajax请求接口
                    var select = "#table-"+form.data("select");//数据列表
                    var pram = "";//搜索字段组装
                    
                    //搜索字段组装
                    var _s = "";
                    var _o = "";
                    //遍历搜索字段
                    $.each($("#"+$(obj).data("form")+" .form-ajax-search"),function (i) {
                        var _eq = $(this).attr("data-_o");
                        var _n = this.name;
                        var _v = this.value;
                        _s += _n + "=" + _v + "|";
                        _o += _n + "=" + _eq + "|";
                        
                        //重置
                        if(type == "reset"){
                            this.value = "";
                            //重置下拉选择框
                            $(this).parents(".d-input").find(".select2-selection__clear").mousedown();
                            $(this).parents(".d-input").mousedown();
                        }
                    });
                    
                    //搜索字段组装
                    if(type != "reset"){
                        _s=_s.substring(0,_s.length-1);
                        _o=_o.substring(0,_o.length-1);
                        pram = "?_s="+_s+"&_o="+_o;
                    }
                    
                    //搜索
                    $.ajax({
                        url: href+pram,
                        type: "GET"
                    }).done(function(data) {
                        //data = $.parseJSON(data);
                        $(select+" tbody").html(data);
                    });
                }
                //订购
                function select_order_ids(obj) {
                    var id = $(obj).data("id");
                    var order_id = $(obj).data("order-id");
                    
                    var html = "";
                    var select = "#table-"+$(obj).data("select");
                    var select2 = "#table-"+$(obj).data("select2");
                    
                    $(select2+" .empty").remove();
                    //判断是否已订购该工程，没有则插入该工程信息
                    var head_obj = $(select+" .new-table-head[data-order-id="+order_id+"]").parents("tr");
                    var head_obj2 = $(select2+" .new-table-head[data-order-id="+order_id+"]").parents("tr");
                    if(head_obj2.length == 0){
                        html = "<tr>"+head_obj.html()+"</tr>";
                        html += "<tr>"+head_obj.next().html()+"</tr>";
                        
                        $(select2+" tbody ").append(html);
                    }
                    //判断是否已订购该工程的定色，没有则在该工程中插入
                    var body_obj = $(select+" .new-table-list-del[data-id="+id+"]").parents("tr");
                    var body_obj2 = $(select2+" .new-table-list-del[data-id="+id+"]").parents("tr");
                    head_obj2 = $(select2+" .new-table-head[data-order-id="+order_id+"]").parents("tr");
                    if(body_obj2.length == 0){
                        html = "<tr>"+body_obj.html()+"</tr>";
                        
                        $(head_obj2).next().after(html);
                    }
                    
                    //订购动画
                    var offset = $(".list-sum").offset();
                    var fly = "<span class=\'fly badge badge-danger\'>1</span>";
                    $(fly).fly({ 
                        start: { 
                            left: event.pageX,//抛物体起点横坐标 
                            top: event.pageY //抛物体起点纵坐标 
                        }, 
                        end: { 
                            left: offset.left + 10,//抛物体终点横坐标 
                            top: offset.top + 10, //抛物体终点纵坐标 
                        } ,
                        onEnd: function(){
                            $(".fly").remove(); //移除dom
                        } //结束回调
                    });
                    
                    //移除订购数据中的“订购”按钮
                    $(select2+" .new-table-list-del[data-id="+id+"]").parents("tr").find(".new-table-list-add").remove();
                    //移除订购数据中的“移除”按钮中的href
                    $(select2+" .new-table-list-del[data-id="+id+"]").attr("data-href","");
                    //计算订购数量
                    list_sum = $(select2+" .new-table-list-del").length;
                    $(".list-sum").html(list_sum);
                    
                }
                //移除
                function select_order_del(obj) {
                    var href = $(obj).data("href");
                    var id = $(obj).data("id");
                    var order_id = $(obj).data("order-id");
                    var pram = "?order_ids="+order_id+"&ids="+id;
                    
                    var select = "#table-"+$(obj).data("select");
                    var select2 = "#table-"+$(obj).data("select2");
                    
                    //删除该工程的定色
                    var body_obj2 = $(select2+" .new-table-list-del[data-id="+id+"]").parents("tr");
                    body_obj2.remove();
                    //判断是否还有已订购该工程的定色，没有则在删除该工程
                    body_obj2 = $(select2+" .new-table-list-del[data-order-id="+order_id+"]").parents("tr");
                    if(body_obj2.length == 0){
                        var head_obj2 = $(select2+" .new-table-head[data-order-id="+order_id+"]").parents("tr");
                        head_obj2.next().remove();
                        head_obj2.remove();
                    }
                    
                    //AJAX请求，取消该定色的采购
                    if(href){
                        $.ajax({
                            url: href+pram,
                            type: "GET"
                        }).done(function(data) {
                            
                            //删除该工程的定色
                            var body_obj = $(select+" .new-table-list-del[data-id="+id+"]").parents("tr");
                            body_obj.remove();
                            //判断是否还有已订购该工程的定色，没有则在删除该工程
                            body_obj = $(select+" .new-table-list-del[data-order-id="+order_id+"]").parents("tr");
                            if(body_obj.length == 0){
                                var head_obj = $(select+" .new-table-head[data-order-id="+order_id+"]").parents("tr");
                                head_obj.next().remove();
                                head_obj.remove();
                            }
                            
                        });
                    }
                    
                    //计算订购数量
                    list_sum = $(select2+" .new-table-list-del").length;
                    $(".list-sum").html(list_sum);
                    
                }
                //查看订购
                function select_order2_show(obj) {
                    
                    var type = $(obj).data("type");
                    if(type == "show"){
                        var select2 = "#form_group_"+$(obj).data("select2");
                        //var height = $(select2).height()+15;
                        var height = $(window).height()-$(".tab-content").offset().top;
                        height = height - 15;
                        var height2 = height-59;
                        
                        
                        $("#form_group_selectorder_search2").css("margin-top","-"+height+"px");
                        $(select2).css("height",height2+"px");
                        $(select2).css("margin-top","-"+height2+"px");
                        
                        $(select2).css("display","block");
                        
                        $(obj).data("type","hidden");
                        $(obj).html("收起");
                    }
                    else{
                        
                        var select2 = "#form_group_"+$(obj).data("select2");
                        var height = 24;
                        
                        $("#form_group_selectorder_search2").css("margin-top","-"+height+"px");
                        
                        $(select2).css("display","none");
                        
                        $(obj).data("type","show");
                        $(obj).html("查看");
                    }
                    
                    
                }
                //生成采购单
                function select_get(obj){
                    var select2 = "#table-"+$(obj).data("select2");
                    var body_obj2 = $(select2+" .new-table-list-del");
                    
                    var order_ids = "";
                    var order_color_ids = "";
                    var type_pid = body_obj2.data("type-pid");
                    $.each(body_obj2,function(i) {
                        if(i == 0){
                            order_ids = $(this).data("order-id");
                            order_color_ids = $(this).data("id");
                        }
                        else {
                            order_ids += ","+$(this).data("order-id");
                            order_color_ids += ","+$(this).data("id");
                        }
                    });
                    if(!order_ids)Dolphin.notify("请选择工程", "danger");
                    else {
                        var href = window.location.href.split("?");//分隔URL和参数
                        window.location.href = href[0]+"?stock_type="+type_pid+"&order_ids="+order_ids+"&order_color_ids="+order_color_ids;
                    }
                    return false;
                    
                };
            </script>';

        //ajax模式
        if(!empty($isajax))return ['head'=>'','data'=>$table_data,'list'=>$list];
        return ['from'=>$from,'css'=>$css,'js'=>$js];
    }
    //喷涂表单，不按确认颜色的工程创建
    //print 0:编辑模式 1:打印模式 2:导出
    public static function from1NotOrderColor($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------
        $table_head = [["[12:1]采购单号：{$data['material_sn']}<div style='text-align: right'>日期：".date('Y-m-d',$data['create_time'])."</div>"]];
        //$table_head = [];
        $table_data = [];

        //批量打印
        $btn_html = "";
        if(!empty($data['id'])){
            $is_add = 'add';
            if($print)$is_add = $print;

            $ids = Db::name('wh_material_goods')
                ->alias('g')
                ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
                ->where(['g.material_id'=>$data['id']])
                ->column('s.id');
            $btn['href'] = url('wh/stock/codePrint',['ids'=>implode(',',$ids)]);
            $btn['title'] = '批量打印';
            $btn_html .= self::showCodeHtml('',$is_add,[$btn]);
        }
        $btn_html .= "<a style='float: right;' class='btn btn-success' onclick=\"goods_add()\" ><i class='fa fa-plus-circle'></i></a>";

        //汇总
        $row_area = 0;//合计面积
        $number = 0;//合计采购量
        $table_data[] = [
            "<div style='text-align: center;'>厂商色号</div>",
            "<div style='text-align: center;'>颜色名称</div>",
            "<div style='text-align: center;'>供应商</div>",
            "<div style='text-align: center;'>类别</div>",
            "<div style='text-align: center;'>类别2</div>",
            "<div style='text-align: center;'>类别3</div>",
            "<div style='text-align: center;'>油温</div>",
            "<div style='text-align: center;'>油漆类型</div>",
            "<div style='text-align: center;'>自编号</div>",
            "<div style='text-align: center;'>现有库存</div>",
            "<div style='text-align: center;'>采购量</div>",
            "<div id='goods_note'><div style='text-align: center;float: left;margin: 7px auto;'></div>".$btn_html."</div>",
        ];
        $table_data2 = [];

        //厂家色号
        foreach ($data['lists'] as $vk=>$vv){

            $is_add = $print;
            if(empty($vv['id']))$is_add = 'add';

            $table_data[] = [
                "[1]
                    <div class='td-80'>
                        <input class='form-control goods' type='hidden' name='goods[id][]' value='{$vv['id']}'>
                        <input class='form-control goods' type='hidden' name='goods[material_id][]' value='{$vv['material_id']}'>
                        <input class='form-control goods' type='hidden' name='goods[order_id][]' value='{$vv['order_id']}'>
                        <input class='form-control goods' type='hidden' name='goods[supplier_id][]' value='{$vv['supplier_id']}'>
                        <input class='form-control goods' type='hidden' name='goods[type_pid][]' value='{$vv['type_pid']}'>
                        <input class='form-control goods' type='hidden' name='goods[type_id][]' value='{$vv['type_id']}'>
                        <input class='form-control goods' type='hidden' name='goods[type_id2][]' value='{$vv['type_id2']}'>
                        <input class='form-control goods' type='hidden' name='goods[type_id3][]' value='{$vv['type_id3']}'>
                        <input class='form-control goods' type='hidden' name='goods[row_area][]' value='{$vv['row_area']}'>
                        <input class='form-control goods' type='hidden' name='goods[color_type_id][]' value='{$vv['color_type_id']}'>
                        <input class='form-control goods' type='hidden' name='goods[color_sn][]' value='{$vv['color_sn']}'>
                        <input class='form-control goods' type='hidden' name='goods[stock_sn][]' value='{$vv['stock_sn']}'>
                        <input class='form-control goods' type='hidden' name='goods[order_color_id][]' value='{$vv['order_color_id']}'>
                        <input class='form-control goods' type='hidden' name='goods[material_name][]' value='{$vv['material_name']}'>
                        <input class='form-control goods' type='hidden' name='goods[model][]' value='{$vv['model']}'>
                        <input class='form-control goods' type='hidden' name='goods[heat][]' value='{$vv['heat']}'>
                    
                    ".self::inputToText('goods[supplier_color][]',$vv['supplier_color'],$print,'display:inline;width: 70%;','input','color').
                "<a class='btn btn-success supplier-color color disable-dch pop' data-href='".url('supplierColorList',['_pop'=>1,'_parent_i'=>'__parent_i__'])."' data-layer=\"{&quot;area&quot;:[&quot;90%&quot;,&quot;95%&quot;],&quot;title&quot;:[&quot;请选择厂家色号&quot;,&quot;font-size:24px;text-align: center;&quot;]}\" onclick=\"supplier_color_list(this)\">查询</a></div>",
                "<div class='td-80 material_name'>{$vv['material_name']}</div>",
                "<div class='td-80 supplier_title'>".(empty($vv['supplier_id'])?'':$data['supplier'][$vv['supplier_id']])."</div>",
                "<div class='td-80 type_title'>".(empty($vv['type_id'])?'':$data['stock_type'][$vv['type_id']])."</div>",
                "<div class='td-80 type_title2'>".(empty($vv['type_id2'])?'':$data['stock_type2'][$vv['type_id2']])."</div>",
                "<div class='td-80 type_title3'>".(empty($vv['type_id3'])?'':$data['stock_type3'][$vv['type_id3']])."</div>",
                "<div class='td-80 heat_title'>".(empty($vv['heat'])?'':self::$heat[$vv['heat']])."</div>",
                "<div class='td-80 color_type_title'>".(empty($vv['color_type_id'])?'':$data['color_type'][$vv['color_type_id']])."</div>",
                "<div class='td-80 color_sn'>{$vv['color_sn']}</div>",
                "<div class='td-80 sum_number'>{$vv['sum_number']}</div>",
                "[0]
                    ".self::inputToText('goods[number][]',$vv['number'],$print,'display:inline;width: 80%;','input','goods')."
                    <a class='btn btn-danger goods goods_del' onclick=\"goods_del(this)\" ><i class='fa fa-times'></i></a>
                    ",
                "[0]
                    <div class='td-80''>".self::showCodeHtml($vv['stock_sn'],$is_add)."</div>",
            ];

            $number += floatval($vv['number']);
        }

        //设置表单项
        $from[] = ['complexTable:12', 'order', '添加采购单信息', $table_data, $table_head];
        //---------------------------------------------工程表单项 end--------------------------------------------

        //---------------------------------------------汇总表单项 start------------------------------------------
        $table_head2 = [['[8:1]']];

        $title = "合计：&nbsp;&nbsp;&nbsp;&nbsp;采购量：{$number}";
        $table_data2[] = [
            "[13:1]<div class='alert-info' style='text-align: right;height: 30px;font-size: 20px;'>{$title}</div>"
        ];
        $table_data2[] = [
            "[13:1]<div style='text-align: left;'>备注</div>"
        ];
        $table_data2[] = [
            "[13:1]".self::inputToText("note",$data['note'],$print,'height: 120px;','textarea')
        ];
        $table_data2[] = [
            "[1:1]<div style='text-align: right;'>审核人</div>",
            "[4:1]",
            "[1:1]<div style='text-align: right;'>审核时间</div>",
            "[4:1]",
        ];

        //设置表单项
        $from[] = ['complexTable:12', 'sum', '汇总', $table_data2, $table_head2];
        //---------------------------------------------汇总表单项 end--------------------------------------------

        //打印模式
        $table_data[] = ["[13:1]<div style='text-align: left;font-weight: 600;'><br>汇总</div>"];
        if(!empty($print))return ['head'=>$table_head,'data'=>array_merge($table_data,$table_head2,$table_data2)];
        return $from;
    }
    //喷涂表单，按确认颜色的工程创建
    //print 0:编辑模式 1:打印模式 2:导出
    public static function from1($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------

        //二级列表表头
        $head = [

            'engineering'           =>  ['engineering', '工程名称'],
            'archives_sn'           =>  ['archives_sn', '档案号'],
            'sales'                 =>  ['sales', '业务代表'],
            'back'                  =>  ['back', '内勤'],

            'supplier_color'        =>  ['supplier_color', '颜色编号'],
            'color'                 =>  ['color', '颜色名称'],
            //'color_sn'              =>  ['color_sn', '系统编号'],
            'type_id'               =>  ['type_id', '类别',$data['stock_type']],
            'color_type_id'         =>  ['color_type_id', '类型',$data['color_type']],
            'quality'               =>  ['quality', '属性',$data['quality']],
            'heat'                  =>  ['heat', '油温',$data['heat']],
            //'supplier_id'           =>  ['supplier_id', '供应商',$data['supplier']],
            'stock_number'          =>  ['stock_number', '库存量(KG)'],
            'row_area'              =>  ['row_area', '采购面积'],
            'sug_number'            =>  ['sug_number', '喷涂覆盖率'],//建议量(kg)
            'number'                =>  ['number', '历史单价'],//采购量(kg)
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        $cospan = count($head);
        $table_head = [["[".$cospan.":1]<div class='layui-row layui-col-space10 new-table-head'>

						<div class='layui-col-md12 new-table-head-flex-2'>
                            <span class='new-table-head-left'>采购编号（{$data['material_sn']}}</span>
                            <span class='new-table-head-right'><i class='layui-icon layui-icon-print'></i>采购单</span>

						</div>
					</div>",]];
        $table_head[] = ["[".$cospan.":1]
                        <div class='layui-row layui-col-space10 new-table-head'>

						<div class='layui-col-md12 new-table-head-flex-2'>
                            <span class='new-table-head-left'>工程列表（详情）</span>

						</div>
					</div>",];

        //定色表头
        $v_head = [];
        foreach ($head as $hk=>$hv){
            $v_head[] = '<div class="new-table-head-2">'.$hv[1].'</div>';
        }
        $table_head[] = $v_head;

        $table_data = [];

        //批量打印
        $btn_html = "";
        if(!empty($data['id'])){
            $is_add = 'add';
            if($print)$is_add = $print;

            $ids = Db::name('wh_material_goods')
                ->alias('g')
                ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
                ->where(['g.material_id'=>$data['id']])
                ->column('s.id');
            $btn['href'] = url('wh/stock/codePrint',['ids'=>implode(',',$ids)]);
            $btn['title'] = '批量打印';
            $btn['class'] = 'btn-primary';
            $btn['style'] = 'margin-left: 30px;';
            $btn_html .= self::showCodeHtml('',$is_add,[$btn]);
        }

        //工程
        foreach ($data['lists'] as $k=>$v){
            //小计
            $lists_sum_arr = [];
            $number_sum = 0;
            //厂家色号
            foreach ($v['lists'] as $vk=>$vv){

                //获取库存
                $vv['stock_number'] = StockModel::getSumNumber($vv);

                //根据定色表头顺序，组装数据
                $i = 1;
                $v_data = [];
                foreach ($head as $hk=>$hv){
                    //如果表头3为“btn”，则为操作按钮
                    if(!empty($hv[2]) && $hv[2] == 'btn'){
                        $v_data[] = "
                            <a class='btn btn-danger new-table-list-del' data-order-id='{$vv['order_id']}' data-order-color-id='{$vv['order_color_id']}' onclick='order_color_del(this)'>移除</a>
                        ";
                    }
                    //如果表头3不为空，则为下拉数据
                    elseif(!empty($hv[2]))$v_data[] = isset($hv[2][$vv[$hv[0]]])?$hv[2][$vv[$hv[0]]]:'';
                    else $v_data[] = isset($vv[$hv[0]])?$vv[$hv[0]]:'';

                    if($i == 1){

                        //采购单数据
                        $v_data[0] .= "
                            <input class='form-control goods' type='hidden' name='goods[id][]' value='{$vv['id']}'>
                            <input class='form-control goods' type='hidden' name='goods[material_id][]' value='{$vv['material_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[order_id][]' value='{$vv['order_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[supplier_id][]' value='{$vv['supplier_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_pid][]' value='{$vv['type_pid']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_id][]' value='{$vv['type_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_id2][]' value='{$vv['type_id2']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_id3][]' value='{$vv['type_id3']}'>
                            <input class='form-control goods' type='hidden' name='goods[row_area][]' value='{$vv['row_area']}'>
                            <input class='form-control goods' type='hidden' name='goods[number][]' value='{$vv['number']}'>
                            <input class='form-control goods' type='hidden' name='goods[supplier_color][]' value='{$vv['supplier_color']}'>
                            <input class='form-control goods' type='hidden' name='goods[color_type_id][]' value='{$vv['color_type_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[color_sn][]' value='{$vv['color_sn']}'>
                            <input class='form-control goods' type='hidden' name='goods[stock_sn][]' value='{$vv['stock_sn']}'>
                            <input class='form-control goods' type='hidden' name='goods[order_color_id][]' value='{$vv['order_color_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[material_name][]' value='{$vv['material_name']}'>
                            <input class='form-control goods' type='hidden' name='goods[model][]' value='{$vv['model']}'>
                            <input class='form-control goods' type='hidden' name='goods[heat][]' value='{$vv['heat']}'>
                        ";
                    }

                    //小计
                    $lists_sum_arr[$hk] = '<div class="new-table-head-2"></div>';

                    $i++;
                }
                $number_sum += $vv['number'];

                $table_data[] = $v_data;

                //汇总
                if(empty($table_total_data2[$vv['stock_sn']])){
                    $vv_total_arr = $vv;
                    $vv_total_arr['number'] = 0;
                    $vv_total_arr['row_area'] = 0;
                    $vv_total_arr['sug_number'] = 0;
                    $vv_total_arr['sum_price'] = 0;

                    $table_total_data2[$vv['stock_sn']] = $vv_total_arr;
                }
                $table_total_data2[$vv['stock_sn']]['number']  += $vv['number'];//合计采购量
                $table_total_data2[$vv['stock_sn']]['row_area']  += $vv['row_area'];//合计面积
                $table_total_data2[$vv['stock_sn']]['sug_number']  += $vv['sug_number'];//合计建议量
                $table_total_data2[$vv['stock_sn']]['sum_price']  += $vv['sum_price'];//合计采购金额


            }

            //小计
            $lists_sum_arr['archives_sn'] = '<div class="new-table-head-2 text-danger">小计</div>';
            $lists_sum_arr['number'] = '<div class="new-table-head-2 text-danger">'.$number_sum.'</div>';
            //$table_data[] = array_values($lists_sum_arr);
        }

        //汇总
        $table_head2 = $table_data2 = [];
        $row_area = 0;//合计面积
        $number = 0;//合计采购量
        //二级列表表头
        $head2 = [
            'supplier_id'           =>  ['supplier_id', '供应商',$data['supplier']],
            'supplier_color'        =>  ['supplier_color', '颜色编号'],
            //'sort'                  =>  ['sort', '编号'],
            'color'                 =>  ['color', '颜色名称'],
            'color_sn'              =>  ['color_sn', '系统编号'],
            'type_id'               =>  ['type_id', '类别',$data['stock_type']],
            'color_type_id'         =>  ['color_type_id', '类型',$data['color_type']],
            'quality'               =>  ['quality', '属性',$data['quality']],
            'heat'                  =>  ['heat', '油温',$data['heat']],
            'stock_number'          =>  ['stock_number', '库存量(KG)'],
            'row_area'              =>  ['row_area', '采购面积'],
            'sug_number'            =>  ['sug_number', '建议采购量'],
            'number'                =>  ['number', '采购量'],
            'price'                 =>  ['price', '采购单价'],
            'sum_price'             =>  ['sum_price', '金额'],
            //'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        $cospan2 = count($head2);
        $table_head2[] = ["[".$cospan2.":1]
                        <div class='layui-row layui-col-space10 new-table-head'>

						<div class='layui-col-md12 new-table-head-flex-2'>
                            <span class='new-table-head-left'>产品列表（汇总）</span>

						</div>
					</div>",];

        //定色表头
        $v_head = [];
        foreach ($head2 as $hk=>$hv){
            $v_head[] = '<div class="new-table-head-2">'.$hv[1].'</div>';
        }
        $table_head2[] = $v_head;

        //遍历合计
        $i = 1;
        $row_area_sum = 0;
        $sug_number_sum = 0;
        $number_sum = 0;
        $sum_price_sum = 0;
        $lists_sum_arr = [];
        foreach ($table_total_data2 as $ttd){

            //合计
            $row_area_sum += $ttd['row_area'];
            $sug_number_sum += $ttd['sug_number'];
            $number_sum += $ttd['number'];
            $sum_price_sum += $ttd['sum_price'];

            $ttd['sort'] = $i;
            $ttd['number'] = "[0:1]
            ".self::inputToText("supplier_color[{$ttd['stock_sn']}][number]",$ttd['number'],$print,'','number','goods supplier_color');
            $ttd['price'] = "[0:1]
            ".self::inputToText("supplier_color[{$ttd['stock_sn']}][price]",$ttd['price'],$print,'','number','goods supplier_color');
            $ttd['sum_price'] = "[0:1]
            ".self::inputToText("supplier_color[{$ttd['stock_sn']}][sum_price]",$ttd['sum_price'],$print,'','number','goods supplier_color');

            $v_data = [];
            foreach ($head2 as $hk=>$hv){
                //如果表头3为“btn”，则为操作按钮
                if(!empty($hv[2]) && $hv[2] == 'btn'){
                    $v_data[] = "
                            <a class='btn btn-danger new-table-list-del' data-stock-sn='{$ttd['stock_sn']}' onclick='order_color_del(this)'>移除</a>
                        ";
                }
                //如果表头3不为空，则为下拉数据
                elseif(!empty($hv[2]))$v_data[] = isset($hv[2][$ttd[$hv[0]]])?$hv[2][$ttd[$hv[0]]]:'';
                else $v_data[] = isset($ttd[$hv[0]])?$ttd[$hv[0]]:'';

                //合计
                $lists_sum_arr[$hk] = '<div class="new-table-head-2"></div>';

            }

            $table_data2[] = $v_data;

            $i++;
        }
        //合计
        /* $row_area_sum = 0;
        $sug_number_sum = 0;
        $number_sum = 0;
        $sum_price_sum = 0;*/
        $lists_sum_arr['supplier_id'] = '<div class="new-table-head-2 text-danger">合计</div>';
        $lists_sum_arr['row_area'] = '<div class="new-table-head-2 text-danger">'.$row_area_sum.'</div>';
        $lists_sum_arr['sug_number'] = '<div class="new-table-head-2 text-danger">'.$sug_number_sum.'</div>';
        $lists_sum_arr['number'] = '<div class="new-table-head-2 text-danger">'.$number_sum.'</div>';
        $lists_sum_arr['sum_price'] = '<div class="new-table-head-2 text-danger">'.$sum_price_sum.'</div>';
        $table_data2[] = array_values($lists_sum_arr);

        //设置表单项
        $from[] = ['complexTable:12', 'order', '', $table_data, $table_head];
        //---------------------------------------------工程表单项 end--------------------------------------------

        //---------------------------------------------汇总表单项 start------------------------------------------
        $table_data2[] = [
            "[13:1]<div style='text-align: left;'>备注</div>"
        ];
        $table_data2[] = [
            "[13:1]".self::inputToText("note",$data['note'],$print,'height: 120px;','textarea')
        ];
        $table_data2[] = [
            "[1:1]<div style='text-align: right;'>审核人</div>",
            "[4:1]",
            "[1:1]<div style='text-align: right;'>审核时间</div>",
            "[4:1]",
        ];

        //设置表单项
        $from[] = ['complexTable:12', 'sum', '', $table_data2, $table_head2];
        //---------------------------------------------汇总表单项 end--------------------------------------------

        //打印模式
        $table_data[] = ["[13:1]<div style='text-align: left;font-weight: 600;'><br>汇总</div>"];
        if(!empty($print))return ['head'=>$table_head,'data'=>array_merge($table_data,$table_head2,$table_data2)];
        return ['from'=>$from,'css'=>'','js'=>''];
    }
    public static function from1_old($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------

        //二级列表表头
        $head = [

            'archives_sn'           =>  ['archives_sn', '档案号'],
            'engineering'           =>  ['engineering', '工程名称'],
            'back'                  =>  ['back', '内勤'],
            'sales'                 =>  ['sales', '业务代表'],

            'supplier_color'        =>  ['supplier_color', '颜色编号'],
            'color'                 =>  ['color', '颜色名称'],
            'color_sn'              =>  ['color_sn', '系统编号'],
            'type_id'               =>  ['type_id', '类别',$data['stock_type']],
            'color_type_id'         =>  ['color_type_id', '类型',$data['color_type']],
            'quality'               =>  ['quality', '属性',$data['quality']],
            'heat'                  =>  ['heat', '油温',$data['heat']],
            'supplier_id'           =>  ['supplier_id', '供应商',$data['supplier']],
            'stock_number'          =>  ['stock_number', '库存(kg)'],
            'row_area'              =>  ['row_area', '采购面积(m²)'],
            'sug_number'            =>  ['sug_number', '建议量(kg)'],
            'number'                =>  ['number', '采购量(kg)'],
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        $cospan = count($head);
        $table_head = [["[".$cospan.":1]<div class='layui-row layui-col-space10 layui-btn-blue new-table-head'>

						<div class='layui-col-md12 new-table-head-flex'>
                            <span>采购编号：{$data['material_sn']}</span>
                            <span>采购人：{$data['nickname']}</span>

						</div>
					</div>",]];
        $table_head[] = ["[".$cospan.":1]
                        <div class='layui-row layui-col-space10 new-table-head'>

						<div class='layui-col-md12 new-table-head-flex new-table-head-flex-2'>
                            <span>采购内容：{$data['type_name']}</span>
                            <span>采购重量：{$data['nickname']}</span>
                            <span>采购形式：关联采购</span>
                            <span>订单状态：<div style='width: 225px;display: inline-block;'>
                            ".self::inputToText("urgent_status",$data['urgent_status'],$print,'','select','',self::$urgent_status)."
                            </div></span>
                            <span>采购日期：".date('Y-m-d',$data['create_time'])."</span>
                            <span>预估到货：
                            ".self::inputToText("address_time",date('Y-m-d',$data['create_time']),$print,'width: 225px;display: inline-block;')."
                            </span>

						</div>
					</div>",];

        //定色表头
        $v_head = [];
        foreach ($head as $hk=>$hv){
            $v_head[] = '<div class="new-table-head-2 layui-btn-blue">'.$hv[1].'</div>';
        }
        $table_head[] = $v_head;

        $table_data = [];

        //批量打印
        $btn_html = "";
        if(!empty($data['id'])){
            $is_add = 'add';
            if($print)$is_add = $print;

            $ids = Db::name('wh_material_goods')
                ->alias('g')
                ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
                ->where(['g.material_id'=>$data['id']])
                ->column('s.id');
            $btn['href'] = url('wh/stock/codePrint',['ids'=>implode(',',$ids)]);
            $btn['title'] = '批量打印';
            $btn['class'] = 'btn-primary';
            $btn['style'] = 'margin-left: 30px;';
            $btn_html .= self::showCodeHtml('',$is_add,[$btn]);
        }

        //工程
        foreach ($data['lists'] as $k=>$v){
            //小计
            $lists_sum_arr = [];
            $number_sum = 0;
            //厂家色号
            foreach ($v['lists'] as $vk=>$vv){

                //获取库存
                $vv['stock_number'] = StockModel::getSumNumber($vv);

                //根据定色表头顺序，组装数据
                $i = 1;
                $v_data = [];
                foreach ($head as $hk=>$hv){
                    //如果表头3为“btn”，则为操作按钮
                    if(!empty($hv[2]) && $hv[2] == 'btn'){
                        $v_data[] = "
                            <a class='btn btn-danger new-table-list-del' data-order-id='{$vv['order_id']}' data-order-color-id='{$vv['order_color_id']}' onclick='order_color_del(this)'>移除</a>
                        ";
                    }
                    //如果表头3不为空，则为下拉数据
                    elseif(!empty($hv[2]))$v_data[] = isset($hv[2][$vv[$hv[0]]])?$hv[2][$vv[$hv[0]]]:'';
                    else $v_data[] = isset($vv[$hv[0]])?$vv[$hv[0]]:'';

                    if($i == 1){

                        //采购单数据
                        $v_data[0] .= "
                            <input class='form-control goods' type='hidden' name='goods[id][]' value='{$vv['id']}'>
                            <input class='form-control goods' type='hidden' name='goods[material_id][]' value='{$vv['material_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[order_id][]' value='{$vv['order_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[supplier_id][]' value='{$vv['supplier_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_pid][]' value='{$vv['type_pid']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_id][]' value='{$vv['type_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_id2][]' value='{$vv['type_id2']}'>
                            <input class='form-control goods' type='hidden' name='goods[type_id3][]' value='{$vv['type_id3']}'>
                            <input class='form-control goods' type='hidden' name='goods[row_area][]' value='{$vv['row_area']}'>
                            <input class='form-control goods' type='hidden' name='goods[number][]' value='{$vv['number']}'>
                            <input class='form-control goods' type='hidden' name='goods[supplier_color][]' value='{$vv['supplier_color']}'>
                            <input class='form-control goods' type='hidden' name='goods[color_type_id][]' value='{$vv['color_type_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[color_sn][]' value='{$vv['color_sn']}'>
                            <input class='form-control goods' type='hidden' name='goods[stock_sn][]' value='{$vv['stock_sn']}'>
                            <input class='form-control goods' type='hidden' name='goods[order_color_id][]' value='{$vv['order_color_id']}'>
                            <input class='form-control goods' type='hidden' name='goods[material_name][]' value='{$vv['material_name']}'>
                            <input class='form-control goods' type='hidden' name='goods[model][]' value='{$vv['model']}'>
                            <input class='form-control goods' type='hidden' name='goods[heat][]' value='{$vv['heat']}'>
                        ";
                    }

                    //小计
                    $lists_sum_arr[$hk] = '<div class="new-table-head-2"></div>';

                    $i++;
                }
                $number_sum += $vv['number'];

                $table_data[] = $v_data;

                //汇总
                if(empty($table_total_data2[$vv['stock_sn']])){
                    $vv_total_arr = $vv;
                    $vv_total_arr['number'] = 0;
                    $vv_total_arr['row_area'] = 0;
                    $vv_total_arr['sug_number'] = 0;
                    $vv_total_arr['sum_price'] = 0;

                    $table_total_data2[$vv['stock_sn']] = $vv_total_arr;
                }
                $table_total_data2[$vv['stock_sn']]['number']  += $vv['number'];//合计采购量
                $table_total_data2[$vv['stock_sn']]['row_area']  += $vv['row_area'];//合计面积
                $table_total_data2[$vv['stock_sn']]['sug_number']  += $vv['sug_number'];//合计建议量
                $table_total_data2[$vv['stock_sn']]['sum_price']  += $vv['sum_price'];//合计采购金额


            }

            //小计
            $lists_sum_arr['archives_sn'] = '<div class="new-table-head-2 text-danger">小计</div>';
            $lists_sum_arr['number'] = '<div class="new-table-head-2 text-danger">'.$number_sum.'</div>';
            //$table_data[] = array_values($lists_sum_arr);
        }

        //汇总
        $table_head2 = $table_data2 = [];
        $row_area = 0;//合计面积
        $number = 0;//合计采购量
        //二级列表表头
        $head2 = [
            'sort'                  =>  ['sort', '编号'],
            'supplier_color'        =>  ['supplier_color', '颜色编号'],
            'color'                 =>  ['color', '颜色名称'],
            'color_sn'              =>  ['color_sn', '系统编号'],
            'type_id'               =>  ['type_id', '类别',$data['stock_type']],
            'color_type_id'         =>  ['color_type_id', '类型',$data['color_type']],
            'quality'               =>  ['quality', '属性',$data['quality']],
            'heat'                  =>  ['heat', '油温',$data['heat']],
            'supplier_id'           =>  ['supplier_id', '供应商',$data['supplier']],
            'stock_number'          =>  ['stock_number', '库存(kg)'],
            'row_area'              =>  ['row_area', '采购面积(m²)'],
            'sug_number'            =>  ['sug_number', '建议量(kg)'],
            'number'                =>  ['number', '采购量(kg)'],
            'price'                 =>  ['price', '采购单价'],
            'sum_price'             =>  ['sum_price', '采购金额'],
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        //定色表头
        $v_head = [];
        foreach ($head2 as $hk=>$hv){
            $v_head[] = '<div class="new-table-head-2">'.$hv[1].'</div>';
        }
        $table_head2[] = $v_head;

        //遍历合计
        $i = 1;
        $row_area_sum = 0;
        $sug_number_sum = 0;
        $number_sum = 0;
        $sum_price_sum = 0;
        $lists_sum_arr = [];
        foreach ($table_total_data2 as $ttd){

            //合计
            $row_area_sum += $ttd['row_area'];
            $sug_number_sum += $ttd['sug_number'];
            $number_sum += $ttd['number'];
            $sum_price_sum += $ttd['sum_price'];

            $ttd['sort'] = $i;
            $ttd['number'] = "[0:1]
            ".self::inputToText("supplier_color[{$ttd['stock_sn']}][number]",$ttd['number'],$print,'','number','goods supplier_color');
            $ttd['price'] = "[0:1]
            ".self::inputToText("supplier_color[{$ttd['stock_sn']}][price]",$ttd['price'],$print,'','number','goods supplier_color');
            $ttd['sum_price'] = "[0:1]
            ".self::inputToText("supplier_color[{$ttd['stock_sn']}][sum_price]",$ttd['sum_price'],$print,'','number','goods supplier_color');

            $v_data = [];
            foreach ($head2 as $hk=>$hv){
                //如果表头3为“btn”，则为操作按钮
                if(!empty($hv[2]) && $hv[2] == 'btn'){
                    $v_data[] = "
                            <a class='btn btn-danger new-table-list-del' data-stock-sn='{$ttd['stock_sn']}' onclick='order_color_del(this)'>移除</a>
                        ";
                }
                //如果表头3不为空，则为下拉数据
                elseif(!empty($hv[2]))$v_data[] = isset($hv[2][$ttd[$hv[0]]])?$hv[2][$ttd[$hv[0]]]:'';
                else $v_data[] = isset($ttd[$hv[0]])?$ttd[$hv[0]]:'';

                //合计
                $lists_sum_arr[$hk] = '<div class="new-table-head-2"></div>';

            }

            $table_data2[] = $v_data;

            $i++;
        }
        //合计
        /* $row_area_sum = 0;
        $sug_number_sum = 0;
        $number_sum = 0;
        $sum_price_sum = 0;*/
        $lists_sum_arr['sort'] = '<div class="new-table-head-2 text-danger">合计</div>';
        $lists_sum_arr['row_area'] = '<div class="new-table-head-2 text-danger">'.$row_area_sum.'</div>';
        $lists_sum_arr['sug_number'] = '<div class="new-table-head-2 text-danger">'.$sug_number_sum.'</div>';
        $lists_sum_arr['number'] = '<div class="new-table-head-2 text-danger">'.$number_sum.'</div>';
        $lists_sum_arr['sum_price'] = '<div class="new-table-head-2 text-danger">'.$sum_price_sum.'</div>';
        $table_data2[] = array_values($lists_sum_arr);

        //设置表单项
        $from[] = ['complexTable:12', 'order', '', $table_data, $table_head];
        //---------------------------------------------工程表单项 end--------------------------------------------

        //---------------------------------------------汇总表单项 start------------------------------------------
        $table_data2[] = [
            "[13:1]<div style='text-align: left;'>备注</div>"
        ];
        $table_data2[] = [
            "[13:1]".self::inputToText("note",$data['note'],$print,'height: 120px;','textarea')
        ];
        $table_data2[] = [
            "[1:1]<div style='text-align: right;'>审核人</div>",
            "[4:1]",
            "[1:1]<div style='text-align: right;'>审核时间</div>",
            "[4:1]",
        ];

        //设置表单项
        $from[] = ['complexTable:12', 'sum', '', $table_data2, $table_head2];
        //---------------------------------------------汇总表单项 end--------------------------------------------

        //打印模式
        $table_data[] = ["[13:1]<div style='text-align: left;font-weight: 600;'><br>汇总</div>"];
        if(!empty($print))return ['head'=>$table_head,'data'=>array_merge($table_data,$table_head2,$table_data2)];
        return ['from'=>$from,'css'=>'','js'=>''];
    }
    //铝卷表单
    //print 0:编辑模式 1:打印模式
    public static function fromPublic($pid = 0,$data = [],$print = 0,$from_data = []){

        //---------------------------------------------工程表单项 start------------------------------------------

        //操作按钮
        $table_head_btn = "<button class='layui-btn goods-submit ajax-post' target-form='form-builder' type='submit'>提交审核</button><button class='layui-btn goods-submit ajax-post' target-form='form-builder' type='submit'>保存采购单</button>";
        $table_head = "<div style='text-align: left'>(No：{$data['material_sn']}){$table_head_btn}";
        $table_data = [];

        //采购单商品字段
        $goods_from_items = [
            'type_id'           =>  ['select:3', 'info[type_id]', '系列', '', $data['stock_type'],'','','info'],
            'material_name'     =>  ['text:3', 'info[material_name]', '名称','','','','','info'],
            'model'             =>  ['text:3', 'info[model]', '规格型号','','','','','info'],
            'quality'           =>  ['select:3', 'info[quality]', '材质','',$data['quality'],'','','info'],
            'supplier_id'       =>  ['select:3', 'info[supplier_id]', '供应商','',$data['supplier'],'','','info'],
            'lot_sn'            =>  ['text:3', 'info[lot_sn]', '批号','','','','','info'],
            'archives_sn'       =>  ['text:3', 'info[archives_sn]', '关联工程','','','','','info'],
            'number'            =>  ['text:3', 'info[number]', '重量','','','','','info'],
            'price'             =>  ['text:3', 'info[price]', '采购单价','','','','','info hidden'],
            'sum_price'         =>  ['text:3', 'info[sum_price]', '采购金额','','','','','info'],
            'urgent_status'     =>  ['select:3', 'info[urgent_status]', '需求','',self::$urgent_status,'','','info'],
            'note'              =>  ['text:3', 'info[note]', '备注','','','','','info'],
            'num'               =>  ['text:3', 'info[num]', '数量','','','','','info'],
        ];

        //设置可编辑表单项
        foreach ($from_data['goods_from_items'] as $fitk=>$fitv){
            $from_items = $goods_from_items[$fitk];
            //值为空，则按默认名称显示，不为空则按该文本显示
            if(!empty($fitv))$from_items[2] = $fitv;
            $from[] = $from_items;
        }

        $add_m_g[] = [
            "<a style='float: right;' class='btn btn-success' onclick=\"goods_add()\" ><i class='layui-icon layui-icon-add-1'></i></a>",
        ];
        $from[] = ['complexTable:12', '_add_m_g_', '', $add_m_g, []];

        //列表组装
        $list_head_arr = [
            'supplier_id'   =>  [
                'field'     =>  'supplier_id',
                'title'     =>  '供应商',
                'type'      =>  'select',
                'type_list' =>  $data['supplier'],
            ],
            'stock_type'    =>  [
                'field'     =>  'type_id',
                'title'     =>  '类别',
                'type'      =>  'select',
                'type_list' =>  $data['stock_type'],
            ],
            'material_name' =>  [
                'field'     =>  'material_name',
                'title'     =>  '名称',
                'type'      =>  'text',
            ],
            'model'         =>  [
                'field'     =>  'model',
                'title'     =>  '规格型号',
                'type'      =>  'text',
            ],
            'quality'       =>  [
                'field'     =>  'quality',
                'title'     =>  '材质',
                'type'      =>  'select',
                'type_list' =>  $data['quality'],
            ],
            'lot_sn'        =>  [
                'field'     =>  'lot_sn',
                'title'     =>  '批号',
                'type'      =>  'text',
            ],
            'sum_number'    =>  [
                'field'     =>  'sum_number',
                'title'     =>  '当前库存(KG)',
                'type'      =>  'text',
            ],
            'sum_num'       =>  [
                'field'     =>  'sum_num',
                'title'     =>  '当前库存(KG)',
                'type'      =>  'text',
            ],
            'archives_sn'   =>  [
                'field'     =>  'archives_sn',
                'title'     =>  '关联工程',
                'type'      =>  'text',
            ],
            'number'        =>  [
                'field'     =>  'number',
                'title'     =>  '采购重量',
                'type'      =>  'text',
            ],
            'num'           =>  [
                'field'     =>  'num',
                'title'     =>  '采购数量',
                'type'      =>  'text',
            ],
            'sum_price'     =>  [
                'field'     =>  'sum_price',
                'title'     =>  '金额',
                'type'      =>  'text',
            ],
            'btn'           =>  [
                'field'     =>  'btn',
                'title'     =>  '操作',
                'type'      =>  'btn',
                'type_list' =>  [
                    "<a class='btn btn-danger goods goods_del' onclick=\"goods_del(this)\" >删除</a>",
                    "<a style='float: right;' class='btn btn-success' onclick=\"goods_edit(this)\" >修改</a>",
                ]
            ],
        ];

        //自定义列表组装
        $list_head_arr_new = [];
        foreach ($from_data['list_head'] as $flhk=>$flhv){
            $list_head_arr_new[$flhk] = $list_head_arr[$flhk];

            if(!empty($flhv))$list_head_arr_new[$flhk]['title'] = $flhv;
        }
        $list_head_arr = $list_head_arr_new;

        //设置表头合并
        $table_head = [["[".count($list_head_arr).":1]".$table_head]];

        //汇总
        $num = 0;//合计数量
        $number = 0;//合计重量

        //批量打印
        $btn_html = "";
        if(!empty($data['id'])){
            $is_add = 'add';
            if($print)$is_add = $print;

            $ids = Db::name('wh_material_goods')
                ->alias('g')
                ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
                ->where(['g.material_id'=>$data['id']])
                ->column('s.id');
            $btn['href'] = url('wh/stock/codePrint',['ids'=>implode(',',$ids)]);
            $btn['title'] = '批量打印';
            $btn_html .= self::showCodeHtml('',$is_add,[$btn]);
        }
        $btn_html .= "<a style='float: right;' class='btn btn-success' onclick=\"goods_add()\" ><i class='fa fa-plus-circle'></i></a>";

        //合计
        $total_head = [];//合计表头
        $total_data = [];//合计值
        //合计字段
        $total_arr = [
            'number'        =>  '合计重量',
            'sum_price'     =>  '合计金额',
        ];

        //自定义列表组装
        $total_arr_new = [];
        foreach ($from_data['total'] as $ftk=>$ftv){
            $total_arr_new[$ftk] = $total_arr[$ftk];

            if(!empty($ftv))$total_arr_new[$ftk] = $ftv;
        }
        $total_arr = $total_arr_new;

        //列表表头
        $list_head = [];
        foreach ($list_head_arr as $lha){
            $style = 'text-align: center;';
            //if($lha['field'] == 'btn') $style = 'width: 80px;';
            $list_head[] = "<div style='{$style}'>{$lha['title']}</div>";
            //"<div id='goods_note'><div style='text-align: center;float: left;margin: 7px auto;'></div>".$btn_html."</div>",

            if(isset($total_arr[$lha['field']])){
                $total_head[] = $total_arr[$lha['field']];
                $total_data[$lha['field']] = 0;
            }
            else {
                $total_head[] = '';
                $total_data[$lha['field']] = '';
            }

        }
        $table_data[] = $list_head;

        //列表数据
        foreach ($data['lists'] as $sak=>$sav){
            $is_add = $print;
            if(empty($sav['id']) || $sav['status'] == 2)$is_add = 1;

            //隐藏数据
            $hidden_input = "[0]
            ";
            foreach ($sav as $sk=>$sv){
                $hidden_input .= "<input class='goods' type='hidden' name='goods[{$sk}][]' value='{$sv}'>";
            }

            //显示数据
            $list_data = [];
            foreach ($list_head_arr as $lhk=>$lha){
                $lhv = '';
                if($lhk == 0)$lhv = $hidden_input;

                //下拉选择
                if($lha['type'] == 'select'){
                    $v = $sav[$lha['field']];
                    if(isset($lha['type_list'][$sav[$lha['field']]]))$v = $lha['type_list'][$sav[$lha['field']]];
                    $lhv .= "<div class='goods goods-title' data-field='{$lha['field']}_title'>{$v}</div>";
                }
                //操作
                elseif ($lha['type'] == 'btn'){
                    $lhv .= "<div class='goods goods-title'>".implode(' ',$lha['type_list'])."</div>";
                }
                //常规文本
                else $lhv .= "<div class='goods goods-title'>{$sav[$lha['field']]}</div>";

                //组装
                $list_data[] = $lhv;

                //合计
                if(isset($sav[$lha['field']]) && isset($total_arr[$lha['field']]))$total_data[$lha['field']] += floatval($sav[$lha['field']]);
            }

            $table_data[] = $list_data;


        }

        //合计
        $table_data[] = $total_head;
        $table_data[] = $total_data;

        //设置表单项
        $from[] = ['complexTable:12', 'order', '', $table_data, $table_head];
        //---------------------------------------------工程表单项 end--------------------------------------------

        //打印模式
        if(!empty($print))return ['head'=>$table_head,'data'=>array_merge($table_data)];
        return ['from'=>$from,'css'=>'','js'=>''];
    }
    //型材表单
    //print 0:编辑模式 1:打印模式
    public static function from3($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------

        //值为空，则按默认名称显示，不为空则按该文本显示

        $data['goods_from_items'] = [
            'supplier_id'       =>  '',
            'type_id'           =>  '',
            'material_name'     =>  '',
            'quality'           =>  '',
            'model'             =>  '',
            'lot_sn'            =>  '',
            'num'               =>  '采购数量',
            'number'            =>  '重量',
            'price'             =>  '',
            'sum_price'         =>  '',
            'urgent_status'     =>  '',
            'archives_sn'       =>  '',
            'note'              =>  '',
        ];

        //列表组装
        $data['list_head'] = [
            'supplier_id'   =>  '',
            'stock_type'    =>  '',
            'material_name' =>  '',
            'model'         =>  '',
            'quality'       =>  '',
            'lot_sn'        =>  '',
            'sum_number'    =>  '',
            'sum_num'       =>  '',
            'archives_sn'   =>  '',
            'number'        =>  '',
            'num'           =>  '',
            'sum_price'     =>  '',
            'btn'           =>  '',
        ];

        //合计字段
        $data['total'] = [
            'number'        =>  '合计重量',
            'sum_price'     =>  '',
        ];

        return self::fromPublic($pid,$data,$print,$data);

    }
    //铝卷表单
    //print 0:编辑模式 1:打印模式
    public static function from4($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------

        //值为空，则按默认名称显示，不为空则按该文本显示

        $data['goods_from_items'] = [
            'type_id'           =>  '',
            'material_name'     =>  '',
            'model'             =>  '',
            'quality'           =>  '',
            'supplier_id'       =>  '',
            'lot_sn'            =>  '',
            'archives_sn'       =>  '',
            'number'            =>  '重量',
            'price'             =>  '',
            'sum_price'         =>  '',
            'urgent_status'     =>  '',
            'note'              =>  '',
        ];

        //列表组装
        $data['list_head'] = [
            'supplier_id'   =>  '',
            'stock_type'    =>  '',
            'material_name' =>  '',
            'model'         =>  '',
            'quality'       =>  '',
            'lot_sn'        =>  '',
            'sum_number'    =>  '',
            'archives_sn'   =>  '',
            'number'        =>  '',
            'sum_price'     =>  '',
            'btn'           =>  '',
        ];

        //合计字段
        $data['total'] = [
            'number'        =>  '合计重量',
            'sum_price'     =>  '',
        ];

        return self::fromPublic($pid,$data,$print,$data);

    }
    //铝板表单
    //print 0:编辑模式 1:打印模式
    public static function from5($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------

        //值为空，则按默认名称显示，不为空则按该文本显示

        $data['goods_from_items'] = [
            'supplier_id'       =>  '',
            'type_id'           =>  '',
            'material_name'     =>  '',
            'quality'           =>  '',
            'model'             =>  '',
            'lot_sn'            =>  '',
            'num'               =>  '采购数量',
            'number'            =>  '重量',
            'price'             =>  '',
            'sum_price'         =>  '',
            'urgent_status'     =>  '',
            'archives_sn'       =>  '',
            'note'              =>  '',
        ];

        //列表组装
        $data['list_head'] = [
            'supplier_id'   =>  '',
            'stock_type'    =>  '',
            'material_name' =>  '',
            'model'         =>  '',
            'quality'       =>  '',
            'lot_sn'        =>  '',
            'sum_number'    =>  '',
            'sum_num'       =>  '',
            'archives_sn'   =>  '',
            'number'        =>  '',
            'num'           =>  '',
            'sum_price'     =>  '',
            'btn'           =>  '',
        ];

        //合计字段
        $data['total'] = [
            'number'        =>  '合计重量',
            'sum_price'     =>  '',
        ];

        return self::fromPublic($pid,$data,$print,$data);

    }
    //化工表单
    //print 0:编辑模式 1:打印模式
    public static function from6($pid = 0,$data = [],$print = 0){

        //---------------------------------------------工程表单项 start------------------------------------------

        //值为空，则按默认名称显示，不为空则按该文本显示

        $data['goods_from_items'] = [
            'type_id'           =>  '',
            'material_name'     =>  '',
            'model'             =>  '',
            'quality'           =>  '',
            'supplier_id'       =>  '',
            'number'            =>  '重量',
            'price'             =>  '',
            'sum_price'         =>  '',
            'urgent_status'     =>  '',
            'note'              =>  '',
        ];

        //列表组装
        $data['list_head'] = [
            'supplier_id'   =>  '',
            'stock_type'    =>  '',
            'material_name' =>  '',
            'model'         =>  '',
            'quality'       =>  '',
            'sum_number'    =>  '',
            'number'        =>  '',
            'sum_price'     =>  '',
            'btn'           =>  '',
        ];

        //合计字段
        $data['total'] = [
            'number'        =>  '合计重量',
            'sum_price'     =>  '',
        ];

        return self::fromPublic($pid,$data,$print,$data);

    }

    // 查看条形码
    //print 0:编辑模式 1:打印模式
    public static function showCodeHtml($stock_sn = '',$print = 0,$btn = []){

        if($print && $print != 'add')return '';

        $html = '';
        if(!empty($btn)){
            foreach ($btn as $b){
                if(empty($b['class']))$b['class'] = ' bg-info-light ';
                if(empty($b['style']))$b['style'] = '';
                $layer = '{&quot;area&quot;:[&quot;80%&quot;,&quot;90%&quot;],&quot;title&quot;:[&quot;'.$b['title'].'&quot;,&quot;font-size:24px;text-align: center;&quot;]}';
                $html .= '<a class="btn disable-dch pop '.$b['class'].'" style="'.$b['style'].'" href="'.$b['href'].'?_pop=1" data-layer="'.$layer.'" _tag="archivesPrint" data-toggle="tooltip" data-original-title="'.$b['title'].'"><i class=""></i>'.$b['title'].'</a>';
            }
        }

        if(is_numeric($print)){
            $url_parm = ['stock_sn'=>$stock_sn];
            $url = url('wh/stock/codePrint',$url_parm)."?_pop=1";
            $layer = '{&quot;area&quot;:[&quot;780px&quot;,&quot;90%&quot;],&quot;title&quot;:[&quot;物料条形码&quot;,&quot;font-size:24px;text-align: center;&quot;]}';

            if(empty($extra['material_id']))$html .= '<a class="btn bg-info-light disable-dch pop" href="'.$url.'&print=0" data-layer="'.$layer.'" _tag="archivesPrint" data-toggle="tooltip" data-original-title="查看"><i class=""></i>查看</a>';
            $html .= '<a class="btn btn-primary disable-dch pop" href="'.$url.'" data-layer="'.$layer.'" _tag="archivesPrint" data-toggle="tooltip" data-original-title="打印"><i class=""></i>打印</a>';
        }

        return $html;
    }

    // 打印模板
    //print 1:打印模式 2:导出模式
    public static function toHtml($pid = 0,$data = [],$print = 1){

        $table_arr = self::getTabFrom($pid,$data,$print);

        //缩放比例
        $table_scaling = 1;

        //$html = '<html><style>th{font-size: 18px;font-weight: bold;}td{}</style><body style="margin: 4px;">';
        $html = '<html><style>th{font-size: 12px;font-weight: bold;}td{font-size: 12px;}</style><body style="margin: 4px;">';

        //头部
        /*$html .= '<table border="1" style="text-align: center;border-collapse: collapse;width: '.(21/$table_scaling).'cm;transform-origin: 0 0;"><thead>
                        <tr><th colspan="12" style="font-size: 25px;font-weight: bold;"><img style="width: 50px;margin-bottom: -20px;" class="td-none" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    ';*/

        $colspan = 12;

        $html .= '<table border="1" style="text-align: center;border-collapse: collapse;transform-origin: 0 0;"><thead>
                        <tr><th colspan="'.$colspan.'" class="head" style="font-size: 25px;font-weight: bold;"><img style="width: 50px;margin-bottom: -20px;" class="td-none" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    ';
        foreach ($table_arr as $tk=>$tv){
            //头
            if($tk == 'head'){
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tkkk=>$tvvv){

                        $v = self::tableParseCell($tvvv);

                        $html .= '
                            <th rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</th>
                            ';
                        if($tkkk == 0)$colspan = $v['colspan'];
                    }
                    $html .= '</tr>';
                }
                $html .= '</thead>';
            }
            //体
            elseif($tk == 'data'){
                $html .= '<tbody>';
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = self::tableParseCell($tvvv);

                        //$v['value'] = str_replace("\n","<br>",$v['value']);
                        $html .= '
                            <td rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</tbody>';
            }
        }
        $html .= '</table>';

        $js = 'window.print();';
        if($print == 2){
            $js = '$("table").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: "",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "采购单",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });';
        }
        //js
        $html .= '
                    <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                    <script src="'.config('template.tpl_replace_string')['__STATIC__'].'/common/js/jquery.table2excel.js?v='.date('Ymd').'"></script>
                    <script type="text/javascript">
                        //设置表头合并
                        $(".head").attr("colspan",'.$colspan.')
                        //删除不显示的元素
                        $(".notPrint").remove()
                        //去除边框
                        $(".td-none").parent().css("border-style","hidden")
                        //设置头部边框
                        $(".td-top").parent().css("border-top","black");
                        //设置底部边框
                        $(".td-bottom").parent().css("border-bottom","black");
                        //设置高度
                        $(".td-50").parent().css("height","50px");
                        //设置向下对齐
                        $(".text-bottom").parent().css("vertical-align","bottom");
                        //设置文字上下间距
                        $(".text-height").parent().css("line-height","28px");
                        //设置文字缩放比例
                        $("th,td").css("-webkit-transform","scale('.$table_scaling.')");
                        //设置文字缩放后左对齐
                        $(".scale-left").parent().css("transform-origin","0");
                        
                        '.$js.'
                    </script>';

        return $html;
    }

    // input框和纯文字互转
    public static function inputToText($field = '',$val = '',$print = 0,$style = '',$input = 'input',$class = '',$select = [],$tips = '',$extra = []){

        $data_html = '';
        if(!empty($extra)){
            foreach ($extra as $ek=>$ev){
                $data_html .= " data-{$ek}='{$ev}' ";
            }
        }


        if($input == 'textarea')$re = "<textarea style='{$style}' class='form-control {$class}' name='{$field}' {$data_html}>{$val}</textarea>";
        elseif ($input == 'date')$re = "<input class='js-datepicker form-control layui-input' type='text' id='{$field}' name='{$field}' value='".(!empty($val)?date('Y-m-d',$val):'')."' {$data_html} data-date-format='yyyy-mm-dd' placeholder='yyyy-mm-dd'>";
        elseif ($input == 'select'){
            $option = '<option value="">请选择或搜索</option>';
            foreach ($select as $k=>$v){
                $selected = '';
                $data_html = '';
                if(is_array($v)){
                    $k = $v['id'];
                    $data_html = $v['data_html'];
                    $v = $v['title'];
                }
                if($k == $val){
                    $selected = " selected ";
                    $val = $v;
                }
                $option .= '<option value="'.$k.'" '.$selected.$data_html.'>'.$v.'</option>';
            }
            $data_html = '';
            if(!empty($extra)){
                if(isset($extra['url'])){
                    $data_html .= " data-table='table' data-extra-param='' ";
                    //$data_html .= " data-url='{$extra['url']}' ";
                    $data_html .= " data-param='{$field}' ";
                    $data_html .= " data-next-items='{$extra['next_field']}' ";
                    $class .= ' select-linkage ';
                }
                foreach ($extra as $ek=>$ev){
                    $data_html .= " data-{$ek}='{$ev}' ";
                }
            }
            //$re = "<select class='js-select2 form-control {$class}' id='{$field}' name='{$field}' {$data_html} data-allow-clear='true' data-placeholder='请选择'>{$option}</select>";
            $re = "<select style='{$style}' class='form-control hidden layui-input {$class}' name='{$field}' {$data_html} lay-search='' lay-filter='{$field}' lay-verify='required' >{$option}</select>";
        }
        else{
            if($input == 'input')$input = 'text';
            $re = "<input style='{$style}' class='form-control layui-input {$class}' type='{$input}' name='{$field}' value='{$val}' {$data_html} />";
        }
        if($tips)$re .= "<div class='help-block'>{$tips}</div>";

        if(!empty($print))return str_replace("\r","</br>",$val);

        return $re;
    }

    // 0：序列化 1：反序列化
    public static function serialize($lists = [],$type = 0,$validate = []){
        $data = [];

        //序列化
        if(empty($type)){
            foreach ($lists as $sk=>$sv){
                foreach ($sv as $skk=>$svv){
                    if(!empty($validate[$sk]) && empty($svv))return $validate[$sk];
                    $data[$skk][$sk] = $svv;
                }
            }
        }
        //反序列化
        else{
            foreach ($lists as $sk=>$sv){
                foreach ($sv as $skk=>$svv){
                    $data[$skk][$sk] = $svv;
                }
            }
        }

        return $data;
    }

    /**
     * 分析单元格合并
     * @param $v
     * @return array
     */
    public static function tableParseCell($v)
    {
        if (preg_match('/\[(.*)\]/', $v, $matches)) {
            $cell  = str_replace($matches[0], '', $v);
            $merge = explode(':', $matches[1]);
            $result = [
                'value'   => $cell,
                'colspan' => $merge[0],
                'rowspan' => isset($merge[1]) ? $merge[1] : '',
            ];
        } else {
            $result = [
                'value'   => $v,
                'rowspan' => '',
                'colspan' => '',
            ];
        }

        return $result;
    }
}
